package org.srx.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbAccess {


	private static String driver = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://localhost:3307/myhome?autoReconnect=true";
	private String user = "root";
	private String password = "root";
//	private String url = "jdbc:mysql://localhost:3307/jikeytang?autoReconnect=true";
//	private String user = "jikeytang";
//	private String password = "ooowww";
	
	private Connection conn = null;
	private Statement st = null;
	private ResultSet rs = null;
	private PreparedStatement ps = null;
	
	/* ����mysql�� */
	static {
		try {
			Class.forName(driver).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/* �õ�Connection */
	public Connection getConn() {
		try {
			this.conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/* �õ�Statement */
	public Statement getStatement() {
		try {
			getConn();
			this.st = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return st;
	}

	/* �õ�PreparedStatement */
	public PreparedStatement getPreparedStatement(String sql) {
		try {
			getConn();
			this.ps = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ps;
	}

	/*
	 * �õ���ѯ���
	 */
	public ResultSet getResultSet(String sql) {
		try {
			getStatement();
			this.rs = st.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	/*
	 * ����
	 */
	public int insertTable(String sql) {
		int num = -1;
		getStatement();
		try {
			num = st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	/*
	 * ����
	 */
	public int updateTable(String sql) {
		int num = -1;
		getStatement();
		try {
			num = st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	/*
	 * ɾ��
	 */
	public int deleteTable(String sql) {
		int num = -1;
		getStatement();
		try {
			num = st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	/*
	 * �ر���ݿ�
	 */
	public void closeDb() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
